﻿using BestTrader.Cms.IRepository;
using BestTrader.Cms.IServices;
using BestTrader.Cms.Models;
using BestTrader.Cms.RmmfSoftServices;
using BestTrader.Cms.ViewModels;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BestTrader.Cms.Services
{
    public class BatchService : IBatchService
    {
        #region 1. 初始化
        private readonly IManagerRepository _managerRepository;
        private readonly IExchangeRateRepository _exchangeRateRepository;
        private readonly IServiceChargeRepository _serviceChargeRepository;
        private readonly ITradeCommissionRepository _tradeCommissionRepository;
        private readonly IRebateRecordRepository _rebateRecordRepository;
        private readonly IRebateExtractRepository _rebateExtractRepository;
        private readonly IHistory_DealedOrderReportRepository _historyRepository;
        private readonly IHistory_CashChangesRepository _historyCashRepository;

        private readonly IRmmfSyncLogService _rmmfLogService;
        private readonly ISysItemsDetailService _itemService;
                
        private readonly IUCAlipayInCashService _payService;
        private readonly IDESEncryptService _desService;

        //private readonly ICacheService _cacheService;
        private readonly RmmfOrderService _rmmfOrderService;
        private readonly RmmfSoftCashService _rmmfCashService;

        private readonly ILogger<BatchService> _logger;

        public BatchService(IManagerRepository managerRepository
            , IExchangeRateRepository exchangeRateRepository
            , IServiceChargeRepository serviceChargeRepository
            , ITradeCommissionRepository tradeCommissionRepository
            , IRebateRecordRepository rebateRecordRepository
            , IRebateExtractRepository rebateExtractRepository
            , IHistory_DealedOrderReportRepository historyRepository
            , IHistory_CashChangesRepository historyCashRepository
            , IRmmfSyncLogService rmmfLogService
            , ISysItemsDetailService itemService
            , IUCAlipayInCashService payService
            , IDESEncryptService desService
            , RmmfOrderService rmmfOrderService
            , RmmfSoftCashService rmmfCashService
            , ILogger<BatchService> logger)
        {
            this._managerRepository = managerRepository;
            this._exchangeRateRepository = exchangeRateRepository;
            this._serviceChargeRepository = serviceChargeRepository;
            this._tradeCommissionRepository = tradeCommissionRepository;
            this._rebateRecordRepository = rebateRecordRepository;
            this._rebateExtractRepository = rebateExtractRepository;
            this._historyRepository = historyRepository;
            this._historyCashRepository = historyCashRepository;
            this._rmmfLogService = rmmfLogService;
            this._itemService = itemService;
            this._payService = payService;
            this._desService = desService;
            this._rmmfOrderService = rmmfOrderService;
            this._rmmfCashService = rmmfCashService;
            this._logger = logger;
        }

        #endregion

        #region 2.1 同步风软交易历史数据
        /// <summary>
        /// 2.1 同步风软交易历史数据
        /// </summary>
        public void RmmfHistoryDealedOrderReportAsync()
        {
            var actionName = "RmmfHistoryDealedOrderReportAsync";
            var now = DateTime.Now.Date;
            var yesterday = now.AddDays(-1);
            _logger.LogWarning($"同步风软交易历史数据:{ yesterday.ToString() }");
#if DEBUG
            //yesterday = new DateTime(2019, 3, 3);
#endif
            // 判断是否同步昨天的数据
            //var history = _historyRepository.Get("Select top 1 * from [dbo].[History_DealedOrderReport] order by AddTime desc");
            //var isNotExist = true;
            //if (history != null)
            //{
            //    if (history.DealedDate.HasValue)
            //        if (history.DealedDate.Value.Date == yesterday) isNotExist = false;
            //}
            var isExist = _rmmfLogService.IsExistCurrentDateRmmfSyncLog(actionName);

            if (!isExist)
            {
                _rmmfLogService.AddOrModify(actionName, 1);
                var userName = "QSADMIN";
                var rmmfHistory = _rmmfOrderService.GetHistoryDealed(yesterday, yesterday, userName);
                _logger.LogWarning($"同步风软交易历史数据交易手数:{ rmmfHistory.Count() }");
                if (rmmfHistory.Any())
                {
                    foreach (var item in rmmfHistory)
                    {
                        var current = new History_DealedOrderReport
                        {
                            AccountName = item.AccountName,
                            ByManual = item.ByManual,
                            Carry_Date = item.Carry_Date,
                            CCustFee = item.NetFee,
                            Currency = item.Currency,
                            CustFee = item.CustFee,
                            CustGroup = item.CustGroup,
                            DataFeeder = item.DataFeederName,
                            DealedAsset = item.DealedAsset,
                            DealedNumber = item.DealedNumber,
                            DealedPrice = item.DealedPrice,
                            DealedDate = item.DealedDate,
                            DealedTime = item.DealedTime,
                            DispExch_Code = item.DisplayDealedPrice,
                            FCM_Code = item.FCM_Code,
                            FCM_Exec_ID = item.FCM_Exec_ID,
                            FCM_Fee = item.FCM_Fee,
                            FCM_Name = item.FCM_Name,
                            ForceClose = item.ForceClose,
                            LastTradingDate = item.LastTradingDate,
                            LMESettleDate = item.LMESettleDate,
                            NodeName = item.NodeName,
                            OptionType = item.OptionType,
                            Order_ID = item.Order_ID,
                            PfCode = item.PfCode,
                            Quantity = item.Quantity,
                            RealName = item.RealName,
                            StrikePrice = item.StrikePrice,
                            TradeSide = item.Side,
                            TradeStyle = item.TradeStyle,
                            UserName = item.userName,
                            AddTime = DateTime.Now,
                            AddManagerId = 0
                        };
                        _logger.LogWarning($"同步风软交易历史数据  AccountName:{ current.AccountName } DealedNumber:{ current.DealedNumber } RealName:{ current.RealName } Order_ID:{ current.Order_ID } Quantity:{ current.Quantity }");
                        _historyRepository.Insert(current);
                    }
                }
            }
        }
        #endregion

        #region 2.2 生成返佣记录
        public void GetRebateRecord()
        {
            GetRebateRecordByTime(null);
        }

        /// <summary>
        /// 2.2 生成返佣记录
        /// </summary>
        public void GetRebateRecordByTime(DateTime? opTime)
        {
            var __infoMsg__ = $"[同步开始]==============================================[{ DateTime.Now }]==============================================[同步开始]";
            _logger.LogError(__infoMsg__);
            #region 1. 获取初始记录

            // 获取最新的一条汇率记录
            var _exchangeRate = _exchangeRateRepository.Get("Select top 1 * from [dbo].[ExchangeRate] where IsDelete = 0 order by ProjectTime desc");
            if (_exchangeRate == null)
            {
                __infoMsg__ = $"失败：未获取到汇率记录";
                _logger.LogError(__infoMsg__);
                return;
            }
            // 获取服务费记录
            var _serviceCharge = _serviceChargeRepository.Get("Select top 1 * from [dbo].[ServiceCharge] where IsDelete = 0 order by ProjectTime desc");
            if (_serviceCharge == null)
            {
                __infoMsg__ = $"失败：未获取到服务费记录";
                _logger.LogError(__infoMsg__);
                return;
            }

            #endregion
            #region 2. 获取所有参数记录
            // 交易产品类型
            var _proTypes = _itemService.GetItems("ProjectType");
            // 货币类型
            var _currencyTypes = _itemService.GetItems("CurrencyType");
            var _managers = _managerRepository.GetList();

            #region 2.1 获取最新的服务费
            // 获取最新的服务费
            var _services = _serviceChargeRepository.GetList($"where IsDelete = 0");
            // 获取默认代理提成记录
            var defautServices = _services.Where(p => p.IsDefault).ToList();
            if (!defautServices.Any())
            {
                __infoMsg__ = $"失败：未获取到服务费记录";
                _logger.LogError(__infoMsg__);
                return;
            }
            var otherServices = _services.Where(p => !p.IsDefault).ToList();
            #endregion
            #region 2.2 获取默认代理和指定代理提成规则记录

            var _trades = _tradeCommissionRepository.GetList($"where IsDelete = 0");
            // 获取默认代理提成记录
            var defautTrades = _trades.Where(p => p.IsDefault).ToList();
            if (!defautTrades.Any())
            {
                __infoMsg__ = $"失败：未获取到默认代理提成记录";
                _logger.LogError(__infoMsg__);
                return;
            }
            // 获取其他代理提成记录
            var otherTrades = _trades.Where(p => !p.IsDefault).ToList();

            // 获取所有代理
            var agents = _managerRepository.GetCacheAllAgentManager();

            #endregion
            #region 2.3 获取默认汇率和指定代理汇率规则记录
            // 获取 汇率表
            var _rates = _exchangeRateRepository.GetList($"where IsDelete = 0");
            var defautRades = _rates.Where(p => p.IsDefault).ToList();
            // 获取默认汇率记录
            if (!defautRades.Any())
            {
                __infoMsg__ = $"失败：未获取到默认汇率规则";
                _logger.LogError(__infoMsg__);
                return;
            }
            // 获取指定代理汇率规则
            var otherRades = _rates.Where(p => !p.IsDefault).ToList();
            #endregion

            #endregion
            #region 3. 计算逻辑

            //var yesterdayStart = DateTime.Now.Date.AddDays(-1).ToString("yyyy-MM-dd HH:mm:ss");
            //var yesterdayEnd = DateTime.Now.Date.AddSeconds(-1).ToString("yyyy-MM-dd HH:mm:ss");
            //var history = _historyRepository.GetList($"where DealedDate >='{ yesterdayStart}' and DealedDate<='{ yesterdayEnd }' and IsDelete = 0");

            var yesterdayStart = DateTime.Now.Date.ToString("yyyy-MM-dd HH:mm:ss");
            var yesterdayEnd = DateTime.Now.Date.AddDays(1).AddSeconds(-1).ToString("yyyy-MM-dd HH:mm:ss");
            if (opTime.HasValue)
            {
                yesterdayStart = opTime.Value.Date.ToString("yyyy-MM-dd HH:mm:ss");
                yesterdayEnd = opTime.Value.Date.AddDays(1).AddSeconds(-1).ToString("yyyy-MM-dd HH:mm:ss");
            }
#if DEBUG
            //yesterdayStart = new DateTime(2019, 3, 9, 0, 0, 1).ToString("yyyy-MM-dd HH:mm:ss");
            //yesterdayEnd = new DateTime(2019, 3, 9, 23, 59, 59).ToString("yyyy-MM-dd HH:mm:ss");
#endif
            var history = _historyRepository.GetList($"where AddTime >='{ yesterdayStart}' and AddTime<='{ yesterdayEnd }' and IsDelete = 0");

            // 计算返佣并显示相关记录
            if (history.Any())
            {
                var now = DateTime.Now;
                foreach (var item in history)
                {
                    var code = item.PfCode;
                    // 交易结算时间
                    var tradingDate = item.DealedDate;

                    var userName = item.UserName;
                    // 使用第三方支付帐号
                    if ($"{userName}01" != item.AccountName && item.AccountName.Length > 2)
                    {
                        __infoMsg__ = $"使用第三方支付帐号:当前用户[{item.UserName}]支付帐号[{item.AccountName}]! ";
                        _logger.LogInformation(__infoMsg__);
                        userName = item.AccountName.Substring(0, item.AccountName.Length - 2);
                    }

                    #region 1. 获取本地数据库[Manager]中相关用户

                    var account = _managers.FirstOrDefault(p => p.UserName == userName);
                    if (account == null)
                    {
                        __infoMsg__ = $"====================失败：用户[Manager]:{userName}不存在! ";
                        _logger.LogError(__infoMsg__);
                        continue;
                    }
                    #region 1.1 获取当前用户的上级代理和顶级代理（营业部）

                    var filterAccount = new int[] { 1, 2, 3, 5 };
                    if (filterAccount.Contains(account.RoleId))
                    {
                        __infoMsg__ = $"ERROR:====================失败:当前用户[{userName}]角色[{account.RoleId}]不能参与交易，请管理员确认! ";
                        _logger.LogError(__infoMsg__);
                        continue;
                    }

                    // 营业部
                    var _rootParentId = 0;
                    // 代理
                    var _parentId = 0;
                    var _parentManagerName = "";
                    var _parentManagerRealName = "";
                    if (account.RoleId == 4)
                    {
                        _parentId = account.Id;
                        _parentManagerName = account.Id.ToString();
                        _parentManagerRealName = account.Id.ToString();
                    }
                    else
                    {
                        _parentId = account.AddManagerId;
                        _parentManagerName = account.AddManagerId.ToString();
                        _parentManagerRealName = account.AddManagerId.ToString();
                    }
                    var agent = agents.FirstOrDefault(p => p.Id == _parentId);
                    if (agent == null)
                    {
                        __infoMsg__ = $"====================失败：获取当前用户的上级代理和顶级代理（营业部）ParentManagerId：{_parentManagerName}!";
                        _logger.LogError(__infoMsg__);
                        continue;
                    }
                    _rootParentId = agent.AddManagerId;
                    _parentManagerName = agent.UserName;
                    _parentManagerRealName = agent.RealName;

                    #endregion

                    #endregion
                    #region 2. 获取本地数据库产品类型

                    var proType = _proTypes.FirstOrDefault(p => p.ItemCode == code);
                    if (proType == null)
                    {
                        __infoMsg__ = $"====================失败：产品代码不存在：{code}! ";
                        _logger.LogError(__infoMsg__);
                        continue;
                    }

                    #endregion
                    #region 3. 获取本地数据库[ServiceCharge]手续费
                    // 获取当前直客的手续费设置
                    var services = otherServices.Where(p => p.ProjectManagerId == account.Id);
                    if (!services.Any()) services = defautServices;

                    // 手续费设置   /ServiceCharge/Index 
                    // 获取默认最新一条记录
                    // 1. 获取最近更新的直客手续费设置记录
                    var service = services.Where(p => p.AddTime <= tradingDate && p.ProjectCode == code).OrderByDescending(p => p.AddTime).FirstOrDefault();
                    // 2. 如果没有最近的手续费设置逻辑，则使用最后一次设置的直客交易规则
                    if (service == null)
                    {
                        service = services.OrderByDescending(p => p.AddTime).FirstOrDefault(p => p.ProjectCode == code);
                    }
                    // 3. 如果没有获取到相关规则，则使用默认的规则
                    if (service == null)
                    {
                        service = defautServices.FirstOrDefault(p => p.ProjectCode == code);
                    }
                    if (service == null)
                    {
                        __infoMsg__ = $"====================失败：手续费设置[ServiceCharge]不存在：{code}!";
                        _logger.LogError(__infoMsg__);
                        continue;
                    }

                    #endregion
                    #region 4. 汇率设置[ExchangeRate]

                    // 汇率设置     /ExchangeRate/Index
                    var rates = otherRades.Where(p => p.ProjectManagerId == _parentId);
                    if (!rates.Any()) rates = defautRades;

                    var rate = rates.FirstOrDefault(p => p.ProjectCode == proType.ItemData);
                    if (rate == null)
                        rate = defautRades.FirstOrDefault(p => p.ProjectCode == proType.ItemData);
                    if (rate == null)
                    {
                        __infoMsg__ = $"====================失败：汇率设置[ExchangeRate]不存在：{proType.ItemData}!";
                        _logger.LogError(__infoMsg__);
                        continue;
                    }

                    #endregion
                    #region 5. 提成设置[TradeCommission]

                    // 提成设置     /TradeCommission/Index
                    // 5.1 获取代理的所有产品提成
                    var trades = otherTrades.Where(p => p.ProjectManagerId == _parentId);
                    // 5.2 如果代理提成不存在，则使用默认代理提成
                    if (!trades.Any()) trades = defautTrades;
                    // 代理提成
                    var trade = trades.FirstOrDefault(p => p.ProjectCode == code);
                    // 如果指定提成规则，则使用默认规则
                    if (trade == null)
                        trade = defautTrades.FirstOrDefault(p => p.ProjectCode == code);

                    if (trade == null)
                    {
                        __infoMsg__ = $"====================失败：提成设置[TradeCommission]不存在：{code}! ";
                        _logger.LogError(__infoMsg__);
                        continue;
                    }

                    #endregion
                    #region 6. 获取货币类型[SysItemsDetail][CurrencyType]

                    var currencyType = _currencyTypes.FirstOrDefault(p => p.ItemCode == proType.ItemData);
                    if (currencyType == null)
                    {
                        __infoMsg__ = $"====================失败：货币类型[SysItemsDetail][CurrencyType]不存在：{proType.ItemData}! ";
                        _logger.LogError(__infoMsg__);
                        continue;
                    }

                    #endregion
                    #region 7. 计算营业部提成和代理提成
                    // 手续费（单边）设置
                    var serviceChargeMoney = service.ProjectPrice;
                    #region 7.1 默认规则和代理设置的规则
                    // 营业部提成
                    var rootRebateMoney = item.Quantity * trade.ProjectPrice;
                    var rootRebateRMBMoney = item.Quantity * trade.ProjectPrice * rate.ProjectPrice;
                    // 代理提成
                    var rebateMoney = item.Quantity * trade.AgentProjectPrice;
                    var rebateRMBMoney = item.Quantity * trade.AgentProjectPrice * rate.ProjectPrice;
                    #endregion
                    #region 7.2 直客设置的规则
                    // 如果直客有单独设置过【手续费】规则
                    // 并且直客的代理【佣金】不为空和营业部的【成本】不为空
                    if (!service.IsDefault && service.SalesTrade.HasValue && service.AgentTrade.HasValue)
                    {
                        // 手续费（单边）设置
                        serviceChargeMoney = service.SalesTrade + service.AgentTrade;
                        // 营业部提成 为直客的
                        rootRebateMoney = item.Quantity * service.SalesTrade;
                        rootRebateRMBMoney = item.Quantity * service.SalesTrade * rate.ProjectPrice;

                        rebateMoney = item.Quantity * service.AgentTrade;
                        rebateRMBMoney = item.Quantity * service.AgentTrade * rate.ProjectPrice;
                    } 
                    #endregion

                    #endregion
                    #region 8. 同步数据库逻辑

                    #region 8.1 获取营业部用户

                    var rootManager = agents.FirstOrDefault(p => p.Id == _rootParentId);
                    if (rootManager == null)
                    {
                        __infoMsg__ = $"====================失败：获取营业部用户不存在parentManagerId：{_parentId}! ";
                        _logger.LogError(__infoMsg__);
                        continue;
                    }

                    #endregion
                    // 当 account.Id == _parentId 时说明当前用户为代理交易，所有ParentManager使用上级营业部
                    var rebateEntity = new RebateRecord()
                    {
                        ManagerId = account.Id,
                        ManagerName = account.UserName,
                        ManagerRealName = account.RealName,
                        ParentManagerId = account.Id == _parentId ? rootManager.Id : _parentId,
                        ParentManagerName = account.Id == _parentId ? rootManager.UserName : _parentManagerName,
                        PManagerRealName = account.Id == _parentId ? rootManager.RealName : _parentManagerRealName,
                        ServiceChargeMoney = serviceChargeMoney,
                        TransactionNo = item.Order_ID,
                        TransactionTime = item.DealedDate,
                        Quantity = item.Quantity,
                        Currency = item.Currency,
                        ProjectCode = proType.ItemCode,
                        ProjectName = proType.ItemName,
                        Remark = account.Id == _parentId ? "代理交易记录" : "直客交易记录",
                        RebateMoney = rebateMoney,
                        RebateRMBMoney = rebateRMBMoney,
                        DealedNumber = item.DealedNumber,
                        AddTime = now
                    };
                    var isExist = _rebateRecordRepository.Get($"select * from RebateRecord where DealedNumber= '{item.DealedNumber}'");
                    if (isExist == null)
                    {
                        var flag = _rebateRecordRepository.Insert(rebateEntity);
                        if (flag > 0)
                        {
                            if (_parentId != 0)
                            {
                                #region 添加代理返佣提现金
                                // 添加代理返佣提现金
                                var rebateFlag = _rebateExtractRepository.Insert(new RebateExtract
                                {
                                    ManagerId = _parentId,
                                    ManagerName = _parentManagerName,
                                    ManagerRealName = _parentManagerRealName,
                                    ExtractRMBType = true,
                                    ExtractRMBMoney = rebateRMBMoney,
                                    State = 0,
                                    ApplyTime = now,
                                    AddManagerId = account.Id,
                                    DealedNumber = item.DealedNumber,
                                    AddTime = now
                                });
                                if (rebateFlag > 0)
                                {
                                    // 入金成功
                                    // 同步数据处理成功
                                    __infoMsg__ = $"返佣提现成功：序号: { rebateFlag }" +
                                                    $"直客编号: { _parentId }" +
                                                    $"直客帐号: { _parentManagerName }" +
                                                    $"直客名称: { _parentManagerRealName }" +
                                                    $"人民币金额: ￥{ rebateRMBMoney }";
                                    _logger.LogInformation(__infoMsg__);
                                }
                                else
                                {
                                    __infoMsg__ = $"失败：插入返佣提现金失败，请重试！";
                                    _logger.LogError(__infoMsg__);
                                }
                                #endregion
                                #region 添加营业部成本提现
                                // 添加营业部成本提现
                                var rootRebateFlag = _rebateExtractRepository.Insert(new RebateExtract
                                {
                                    ManagerId = rootManager.Id,
                                    ManagerName = rootManager.UserName,
                                    ManagerRealName = rootManager.RealName,
                                    ExtractRMBType = true,
                                    ExtractRMBMoney = rootRebateRMBMoney,
                                    State = 0,
                                    ApplyTime = now,
                                    AddManagerId = account.Id,
                                    DealedNumber = item.DealedNumber,
                                    AddTime = now
                                });
                                if (rootRebateFlag > 0)
                                {
                                    // 入金成功
                                    // 同步数据处理成功
                                    __infoMsg__ = $"营业部成本成功!序号: { rootRebateFlag }" +
                                                    $"直客编号: { rootManager.Id }" +
                                                    $"直客帐号: { rootManager.UserName }" +
                                                    $"直客名称: { rootManager.RealName }" +
                                                    $"人民币金额: ￥{ rootRebateRMBMoney }";
                                    _logger.LogInformation(__infoMsg__);
                                }
                                else
                                {
                                    __infoMsg__ = $"同步失败：时间：{ DateTime.Now } 插入返佣提现金失败，请重试！";
                                    _logger.LogError(__infoMsg__);
                                }
                                #endregion
                            }
                            else
                            {
                                __infoMsg__ = $"失败：未找相关代理营业部rootManagerId：{ rootManager.Id }！";
                                _logger.LogError(__infoMsg__);
                            }

                            // 同步数据处理成功
                            __infoMsg__ = $"返佣记录序号: { item.Order_ID}" +
                                            $"直客帐号: { userName }" +
                                            $"手续费(单边): {currencyType.ItemData}{ serviceChargeMoney }" +
                                            $"成交编号: { item.Order_ID}" +
                                            $"成交时间: { item.DealedDate }" +
                                            $"成交数量: { item.Quantity }" +
                                            $"产品类型: { code }" +
                                            $"返佣说明: " +
                                            $"货币类型: { proType.ItemData }" +
                                            $"返佣金额: {currencyType.ItemData}{ rebateMoney }" +
                                            $"人民币金额: ￥{ rebateRMBMoney }";
                            _logger.LogInformation(__infoMsg__);
                        }
                        else
                        {
                            __infoMsg__ = $"失败：插入返佣记录失败，请重试！";
                            _logger.LogError(__infoMsg__);
                        }
                    }
                    else
                    {
                        __infoMsg__ = $"重复数据订单{ item.DealedNumber }";
                        _logger.LogWarning(__infoMsg__);
                    }
                    #endregion
                }
            }
            else
            {
                __infoMsg__ = $"成功：未找到任何子账户成交历史记录";
                _logger.LogWarning(__infoMsg__);
            }
            #endregion

            __infoMsg__ = $"[同步结束]==============================================[{ DateTime.Now }]==============================================[同步结束]";
            _logger.LogError(__infoMsg__);
        }

        public void SyncEnManager()
        {
            var list = _managerRepository.GetList();
            foreach (var item in list)
            {
                var newManager = _desService.EncryptManagerInfo(item);
                _managerRepository.Update(newManager);
            }
        }

        ///// <summary>
        ///// 3.1 第三方支付订单同步
        ///// </summary>
        //public void YunPayOrderSync() {
        //    // 订单完成状态(0:等待付款；1:付款完成；2:订单超时；3:订单不存在或者超时被删除；4:token错误)
        //    var model = new UCAlipayInCashRequestModel {
        //        Key = "0" // "0,2,3,4"
        //    };
        //    var res = _payService.LoadUnfinishedData(model);

        //    _payService.UpdateUCAlipayInCashState(res).Wait();
        //}
        #endregion

        /// <summary>
        /// 3.0 生成历史出入金记录
        /// </summary>
        public void RmmfCashHistoryReportAsync()
        {
            var actionName = "RmmfCashHistoryReportAsync";
            var now = DateTime.Now.Date;
            var yesterdayStart = now.AddDays(-2);
            var yesterdayEnd = now.AddDays(-1);
            //var yesterdayStart = now.AddDays(-3);
            //var yesterdayEnd = now.AddDays(-2);
            _logger.LogWarning($"同步风软历史出入金数据:{ yesterdayStart.ToString() }");

            var isExist = _rmmfLogService.IsExistCurrentDateRmmfSyncLog(actionName);

            if(!isExist)
            {
                _rmmfLogService.AddOrModify(actionName, 1);
                // 资金编号
                var accountId = "";
                var rmmfHistory = _rmmfCashService.GetCashChangesByAccountAndOrDateTime(yesterdayStart, yesterdayEnd, accountId);
                _logger.LogWarning($"同步风软历史出入金数据交易手数:{ rmmfHistory.Count() }");
                if (rmmfHistory.Any())
                {
                    foreach (var item in rmmfHistory)
                    {
                        var current = new History_CashChanges{
                            CashChangesID = item.ID,
                            Account_ID = item.Account_ID,
                            AccountName = item.AccountName,
                            Action_Time = item.Action_Time,
                            Amount = item.Amount,
                            Cash_State = item.Cash_State,
                            CurrencyCode = item.CurrencyCode,
                            DisPoser = item.DisPoser,
                            DisPoseTime = item.DisPoseTime,
                            IsProcessed = item.IsProcessed,
                            IsDispose = item.IsDispose,
                            Remark = item.Remark,
                            CreatedBy = item.CreatedBy,
                            AddTime = DateTime.Now,
                            AddManagerId = 0,
                            IsDelete = false
                        };
                        _logger.LogWarning($"同步风软历史出入金数据！  AccountName:{ current.AccountName } Account_ID:{ current.Account_ID } CurrencyCode:{ current.CurrencyCode } Amount:{ current.Amount } CurrencyCode:{ current.CurrencyCode } Remark:{ current.Remark }");
                        _historyCashRepository.Insert(current);
                    }
                }
            }
        }

    }
}
